<?php
/**
 * Created by PhpStorm.
 * User: yangwang
 * Date: 2024-04-25
 * Time: 17:30
 */

namespace App\Console\Commands\Shop;


use App\Enums\WorkOrder\OrderEnum;
use App\Models\Common\ResourcesModel;
use App\Models\Cruise\CruiseShopLicenseRecordsModel;
use App\Models\Cruise\CruiseShopLicenseResourceRecordsModel;
use App\Models\Recognize\RecognizeBusinessLicenseResult;
use App\Models\Recognize\RecognizeFoodProduceLicenseResult;
use App\Models\Shop\ShopModel;
use App\Models\WorkOrder\WorkOrderApplyContentModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class SyncShopLicenseCommand extends Command
{
    protected $signature = 'shop:sync-shop-license';

    protected $description = '初始化门店证件审核数据';

    public function handle()
    {
        $this->info('执行开始');
        ShopModel::query()->chunk(100, function (Collection $shopList) {

            $shopIds = $shopList->pluck('id')->toArray();

            //shop_records..
            $formatList = [];

            WorkOrderApplyMainModel::query()
                                   ->leftJoin(
                                       (new WorkOrderApplyContentModel())->getTable() . ' as co',
                                       (new WorkOrderApplyMainModel())->getTable() . ".workOrderNo", '=',
                                       'co.workOrderNo'
                                   )
                                   ->leftJoin((new ResourcesModel())->getTable() . ' as resource',
                                       'co.id', '=', 'resource.businessId'
                                   )
                                   ->whereIn('shopId', $shopIds)
                                   ->where('problemPid', OrderEnum::PROBLEM_PID_5)
                                   ->where('status', OrderEnum::MAIN_STATUS_FINISH)
                                   ->where('resource.module', ResourcesModel::MODULE_TYPE_WORK_ORDER)
                                   ->where('resource.business', ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN)
                                   ->whereIn('resource.name', ['businessLicenseImg', 'foodBusinessLicenseImg'])
                                   ->orderBy('resource.createdAt', 'desc')
                                   ->select(['*'])
                                   ->chunk(100, function (Collection $applyMainList) use (&$formatList) {
                                       $urls                = $applyMainList->pluck('url')->toArray();
                                       $businessLicenseList = RecognizeBusinessLicenseResult::query()
                                                                                            ->whereIn('url', $urls)
                                                                                            ->get()
                                                                                            ->keyBy('url');
                                       $foodLicenseList     = RecognizeFoodProduceLicenseResult::query()
                                                                                               ->whereIn('url', $urls)
                                                                                               ->get()
                                                                                               ->keyBy('url');

                                       //shopId
                                       foreach ($applyMainList as $applyMain) {
                                           $shopId = $applyMain->shopId;
                                           $name   = $applyMain->name;


                                           if (isset($formatList[$shopId][$name])) {
                                               continue;
                                           }
                                           //证件状态
                                           $licenseEndDate = ($name == 'businessLicenseImg')
                                               ? optional($businessLicenseList[$applyMain->url])->validPeriod
                                               : optional($foodLicenseList[$applyMain->url])->validToDate;

                                           $licenseEndDateTimestamp = $licenseEndDate
                                               ? strtotime($licenseEndDate)
                                               : strtotime(CruiseShopLicenseResourceRecordsModel::LICENSE_FOREVER_DATE);
                                           if (
                                               CruiseShopLicenseResourceRecordsModel::licenseIsForever(
                                                   $licenseEndDateTimestamp
                                               )
                                               || $licenseEndDateTimestamp > time()
                                           ) {

                                               $status = CruiseShopLicenseRecordsModel::STATUS_PENDING;
                                           } else {
                                               $status = CruiseShopLicenseRecordsModel::STATUS_EXPIRED;
                                           }


                                           //format数据
                                           if ($name == 'businessLicenseImg'
                                               && ($businessItem = $businessLicenseList[$applyMain->url] ?? '')
                                           ) {
                                               $formatList[$shopId]['businessLicenseImg'] = [
                                                   'url'              => $applyMain->url,
                                                   'licenceNumber'    => $businessItem->registerNumber,//证件编号
                                                   'businessScope'    => $businessItem->business,//营业范围
                                                   'businessAddress'  => $businessItem->address,//地址
                                                   'legalPerson'      => $businessItem->legalPerson,//法人
                                                   'name'             => '',//营业执照主体名
                                                   'licenseName'      => $businessItem->name,//营业执照主体名
                                                   'type'             => $businessItem->type,//营业主体类型
                                                   'licenseStartDate' => $businessItem->establishDate
                                                       ? strtotime($businessItem->establishDate) : 0,
                                                   'licenseEndDate'   => $licenseEndDateTimestamp,
                                                   'status'           => $status,
                                                   'isPublic'         => $applyMain->isPublic ?? null
                                               ];
                                           }

                                           if ($name == 'foodBusinessLicenseImg'
                                               && ($foodLicenseItem = $foodLicenseList[$applyMain->url] ?? '')
                                           ) {
                                               $formatList[$shopId]['foodBusinessLicenseImg'] = [
                                                   'url'              => $applyMain->url,
                                                   'licenceNumber'    => $foodLicenseItem->licenceNumber,//证件编号
                                                   'businessScope'    => $foodLicenseItem->foodType,//营业范围
                                                   'businessAddress'  => $foodLicenseItem->officeAddress,//地址
                                                   'legalPerson'      => $foodLicenseItem->legalRepresentative,//法人
                                                   'name'             => '',//经营者名称
                                                   'licenseName'      => $foodLicenseItem->producerName,//经营者名称
                                                   'licenseStartDate' => $foodLicenseItem->issueDate
                                                       ? strtotime($foodLicenseItem->issueDate) : 0,
                                                   'licenseEndDate'   => $licenseEndDateTimestamp,

                                                   'productionAddress' => $foodLicenseItem->productionAddress,//经营场所
                                                   'creditCode'        => $foodLicenseItem->creditCode,//社会信用代码

                                                   'mainBusiness' => '',//主体业态
                                                   'status'       => $status,
                                                   'isPublic'     => $applyMain->isPublic ?? null
                                               ];
                                           }
                                       }
                                   });

            $insertRecordList = [];
            foreach ($shopList as $shop) {
                $status             = CruiseShopLicenseRecordsModel::getStatus(
                    $formatList[$shop->id]['businessLicenseImg']['status'] ?? 0,
                    $formatList[$shop->id]['foodBusinessLicenseImg']['status'] ?? 0
                );
                $insertRecordList[] = [
                    'shopId'    => $shop->id,
                    'status'    => $status,
                    'createdAt' => time(),
                    'updatedAt' => time(),
                ];
            }

            CruiseShopLicenseRecordsModel::query()->insert($insertRecordList);

            $this->info("插入records数据:" . count($insertRecordList) . "条");

            $insertResourceList = [];
            foreach ($formatList as $shopId => $formatItem) {
                foreach ($formatItem as $type => $item) {
                    $insertResourceList[] = [
                        'shopId'           => $shopId,
                        'type'             => ($type == 'businessLicenseImg')
                            ? CruiseShopLicenseResourceRecordsModel::TYPE_BUSINESS_LICENSE
                            : CruiseShopLicenseResourceRecordsModel::TYPE_FOOD_LICENSE,
                        'status'           => $item['status'],
                        'url'              => $item['url'],
                        'name'             => $item['name'],
                        'licenceNumber'    => $item['licenceNumber'],
                        'legalPerson'      => $item['legalPerson'],
                        'licenseStartDate' => $item['licenseStartDate'],
                        'licenseEndDate'   => $item['licenseEndDate'],
                        'contents'         => json_encode([
                            'licenseName'       => $item['licenseName'] ?? '',
                            'businessScope'     => $item['businessScope'] ?? '',
                            'businessAddress'   => $item['businessAddress'] ?? '',
                            'productionAddress' => $item['productionAddress'] ?? '',
                            'mainBusiness'      => $item['mainBusiness'] ?? '',
                            'creditCode'        => $item['creditCode'] ?? '',
                            'isPublic'          => $item['isPublic'] ?? '',
                        ], JSON_UNESCAPED_UNICODE),
                        'createdAt'        => time(),
                        'updatedAt'        => time()
                    ];
                }
            }

            CruiseShopLicenseResourceRecordsModel::query()->insert($insertResourceList);
            $this->info("插入resource:" . count($insertResourceList) . "条,涉及门店:" . count($formatList));

        });
        $this->info('执行完成');

    }


}